package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.jxc.abstracts.AbstractJxcAddDataService;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.pojo.vo.FormDataAddVO;
import com.xbongbong.paas.service.dynamic.help.DynamicHelp;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.FormDataUtil;
import com.xbongbong.pro.enums.errorcodes.BuinessDefaultErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.vo.BeforeSaveVO;
import com.xbongbong.pro.formdata.pojo.vo.SaveVO;
import com.xbongbong.saas.domain.entity.CostAdjustSubDataEntity;
import com.xbongbong.saas.domain.entity.ext.CostAdjustEntityExt;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CostAdjustEnum;
import com.xbongbong.saas.help.SaasSaveHelp;
import com.xbongbong.saas.model.CostAdjustModel;
import com.xbongbong.saas.model.CostAdjustSubDataModel;
import com.xbongbong.saas.service.CostAdjustService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author WuHB
 * @date 2021/11/23 16:59
 */
@Service("costAdjustFormDataService")
public class CostAdjustFormDataServiceImpl extends AbstractJxcAddDataService {

    private static final Logger LOG = LoggerFactory.getLogger(CostAdjustFormDataServiceImpl.class);

    @Resource
    private SaasSaveHelp saasSaveHelp;

    @Resource
    private CostAdjustService costAdjustService;

    @Resource
    private CostAdjustModel costAdjustModel;
    @Resource
    private DynamicHelp dynamicHelp;
    @Resource
    private CostAdjustSubDataModel costAdjustSubDataModel;

    @Override
    public List<Integer> businessList() {
        return Arrays.asList(XbbRefTypeEnum.COST_ADJUST.getCode());
    }

    /**
     * 新建保存入口
     *
     * @param formDataAddDTO 添加表单数据实体
     * @param beforeSaveVO   前置保存新信息
     * @return 保存的信息
     * @throws XbbException 一次
     */
    @Override
    public SaveVO save(FormDataAddDTO formDataAddDTO, BeforeSaveVO beforeSaveVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity) throws XbbException {
        Long dataId = 0L;
        String corpid = formDataAddDTO.getCorpid();
        Integer saasMark = formDataAddDTO.getSaasMark();
        Integer businessType = formDataAddDTO.getBusinessType();
        try {
            UserVO userVO = getUserName(formDataAddDTO, paasFormDataEntity);
            Integer noApprovalRequired = beforeSaveVO.getNoApprovalRequired();
            if (Objects.equals(1, noApprovalRequired)) {

                CostAdjustEntityExt costAdjusEntityExt = new CostAdjustEntityExt();
                BeanUtil.copyProperties(paasFormDataEntity, costAdjusEntityExt);
                // 关联产品特殊处理
                JSONObject costAdjusDataList = costAdjusEntityExt.getData();
                // 移掉字段
                FormDataUtil.removeSystemData(costAdjusDataList);
                Object richTextData = removeRichText(costAdjusDataList);
                //costAdjusDataList.put(CostAdjustEnum.WAREHOUSE_ID.getAttr(), null);
                JSONArray productArray = saasSaveHelp.formatSelectProduct4Save2(costAdjusDataList, CostAdjustEnum.PRODUCT.getAttr());
                costAdjusEntityExt.setData(costAdjusDataList);
                costAdjustModel.insert(costAdjusEntityExt);
                dataId = costAdjusEntityExt.getId();
                costAdjusEntityExt.getData().put(CostAdjustEnum.PRODUCT.getAttr(), productArray);
                // 设置属性用于返回
                setPartialAttributes(dataId, costAdjusEntityExt.getSubFormData(), costAdjusEntityExt.getData(), costAdjusEntityExt.getAddTime(),
                        costAdjusEntityExt.getUpdateTime(), paasFormDataEntity, beforeSaveVO);
                //文件柜数据保存
                saveFile(formDataAddDTO, paasFormDataEntity, userVO);
                //富文本数据保存
                saveRichText(formDataAddDTO, paasFormDataEntity, richTextData);
            }
            return new SaveVO(noApprovalRequired, paasFormDataEntity, dataId, userVO);
        } catch (XbbException e) {
            LOG.warn(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(), e);
            saveRollBack(dataId, corpid, saasMark, businessType);
            throw e;
        } catch (Exception e) {
            LOG.error(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(), e);
            saveRollBack(dataId, corpid, saasMark, businessType);
            throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200018);
        }
    }

    @Override
    public void saveRollBack(Long id, String corpid, Integer saasMark, Integer businessType) throws XbbException {
        if (id == null || id == 0 || corpid == null || saasMark == null) {
            return ;
        }
        IndexTypeEnum indexTypeEnum = getIndexTypeEnum(corpid, saasMark, businessType);
        //删除主表es数据
        physicalDeleteFormData(id, corpid, indexTypeEnum);
        // 子表单的删除
        List<CostAdjustSubDataEntity> subDataEntityList = costAdjustSubDataModel.getByDataId(id, corpid);
        if (!subDataEntityList.isEmpty()) {
            physicalDeleteSubBatch(corpid, subDataEntityList, IndexTypeEnum.IDX_SAAS_COST_ADJUST_SUB);
        }
    }

    /**
     * 新建保存之后的逻辑，保存日志、触发业务规则等操作
     *
     * @param formDataAddDTO
     * @param beforeSaveVO   保存之前的方法返回的数据
     * @param saveVO         保存方法返回的数据
     * @return com.xbongbong.pro.formdata.pojo.vo.SaveVO
     * @throws XbbException 异常
     */
    @Override
    public FormDataAddVO afterSave(FormDataAddDTO formDataAddDTO, BeforeSaveVO beforeSaveVO, SaveVO saveVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity) throws XbbException {
        FormDataAddVO formDataAddVO = new FormDataAddVO();
        Long dataId = saveVO.getDataId();
        String corpid = formDataAddDTO.getCorpid();
        Integer saasMark = formDataAddDTO.getSaasMark();
        Integer businessType = formDataAddDTO.getBusinessType();
        try {
            if (Objects.equals(1, saveVO.getNoApprovalRequired())) {
                SaasFormSaveDTO saasFormSaveDTO = new SaasFormSaveDTO();
                BeanUtil.copyProperties(formDataAddDTO, saasFormSaveDTO);
                saasFormSaveDTO.setSaasNeedRedundantAttrPoJo(beforeSaveVO.getSaasNeedRedundantAttrPojo());
                packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);

                costAdjustService.afterSave(saasFormSaveDTO);

                // log
                afterSaveLog(formDataAddDTO, paasFormEntity, paasFormDataEntity, saveVO, beforeSaveVO);
                // 动态处理
                dynamicHelp.addLinkData(saasFormSaveDTO);
                // api
                apiHook(formDataAddDTO, saveVO, beforeSaveVO);
                // 业务规则
                activeRule(formDataAddDTO, beforeSaveVO, paasFormDataEntity, beforeSaveVO.getPaasFormEntityExt());
                formDataAddVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_RETURN_MSG));
                formDataAddVO.setCode(PaasConstant.FORM_ADD_RETURN_CODE);
                formDataAddVO.setDataId(saveVO.getDataId());
                formDataAddVO.setFormDataId(saveVO.getDataId());
            } else {
                formDataAddVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_PROCESS_RETURN_MSG));
                formDataAddVO.setCode(PaasConstant.FORM_ADD_PROCESS_RETURN_CODE);
            }
            return formDataAddVO;
        } catch (XbbException e) {
            LOG.warn(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(), e);
            saveRollBack(dataId, corpid, saasMark, businessType);
            throw e;
        } catch (Exception e) {
            LOG.error(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(), e);
            saveRollBack(dataId, corpid, saasMark, businessType);
            throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200018);
        }
    }

    /**
     * 插入后保存日志
     *
     * @param formDataAddDTO        添加表单数据实体
     * @param newPaasFormDataEntity 新的paas表单实体
     * @param saveVO                保存方法返回的数据
     * @param beforeSaveVO          前置保存新信息
     * @throws XbbException
     */
    @Override
    public void afterSaveLog(FormDataAddDTO formDataAddDTO, PaasFormEntityExt paasFormEntityExt, PaasFormDataEntity newPaasFormDataEntity, SaveVO saveVO, BeforeSaveVO beforeSaveVO) throws XbbException {
        boolean isImport = Objects.equals(1, formDataAddDTO.getIsImport());
        if (isImport) {
            return;
        }
        String serialNo = newPaasFormDataEntity.getSerialNo();
        String name = XbbRefTypeEnum.getByCode(formDataAddDTO.getBusinessType()).getName();
        saveLogger(formDataAddDTO, newPaasFormDataEntity, serialNo, name, OperateModuleTypeEnum.COST_ADJUST, saveVO, beforeSaveVO);
    }

    /**
     * 发起 api
     *
     * @param formDataAddDTO
     * @param saveVO
     * @param beforeSaveVO
     * @return void
     * @throws XbbException
     */
    @Override
    public void apiHook(FormDataAddDTO formDataAddDTO, SaveVO saveVO, BeforeSaveVO beforeSaveVO) throws XbbException {
        lowCodeExecuteService(formDataAddDTO, saveVO, beforeSaveVO);
    }

    /**
     * 新建保存入口
     *
     * @param formDataAddDTO
     * @param beforeSaveVO
     * @return com.xbongbong.pro.formdata.pojo.vo.SaveVO
     * @throws XbbException
     */
    @Override
    public SaveVO saveForWorkflow(FormDataAddDTO formDataAddDTO, BeforeSaveVO beforeSaveVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity) throws XbbException {
        Long dataId = 0L;
        String corpid = formDataAddDTO.getCorpid();
        Integer saasMark = formDataAddDTO.getSaasMark();
        Integer businessType = formDataAddDTO.getBusinessType();
        try {
            UserVO userVO = getUserName(formDataAddDTO, paasFormDataEntity);
            Integer noApprovalRequired = beforeSaveVO.getNoApprovalRequired();
            CostAdjustEntityExt costAdjusEntityExt = new CostAdjustEntityExt();
            BeanUtil.copyProperties(paasFormDataEntity, costAdjusEntityExt);
            // 关联产品特殊处理
            JSONObject costAdjusDataList = costAdjusEntityExt.getData();
            // 移掉字段
            FormDataUtil.removeSystemData(costAdjusDataList);
            Object richTextData = removeRichText(costAdjusDataList);
            costAdjusDataList.put(CostAdjustEnum.WAREHOUSE_ID.getAttr(), null);
            JSONArray productArray = saasSaveHelp.formatSelectProduct4Save2(costAdjusDataList, CostAdjustEnum.PRODUCT.getAttr());
            costAdjusEntityExt.setData(costAdjusDataList);
            costAdjustModel.insert(costAdjusEntityExt);
            dataId = costAdjusEntityExt.getId();
            costAdjusEntityExt.getData().put(CostAdjustEnum.PRODUCT.getAttr(), productArray);
            // 设置属性用于返回
            setPartialAttributes(dataId, costAdjusEntityExt.getSubFormData(), costAdjusEntityExt.getData(), costAdjusEntityExt.getAddTime(),
                    costAdjusEntityExt.getUpdateTime(), paasFormDataEntity, beforeSaveVO);
            //文件柜数据保存
            saveFile(formDataAddDTO, paasFormDataEntity, userVO);
            //富文本数据保存
            saveRichText(formDataAddDTO, paasFormDataEntity, richTextData);
            return new SaveVO(noApprovalRequired, paasFormDataEntity, dataId, userVO);
        } catch (XbbException e) {
            LOG.warn(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(), e);
            saveRollBack(dataId, corpid, saasMark, businessType);
            throw e;
        } catch (Exception e) {
            LOG.error(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(), e);
            saveRollBack(dataId, corpid, saasMark, businessType);
            throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200018);
        }
    }

    /**
     * 新建保存之后的逻辑，保存日志、触发业务规则等操作
     *
     * @param formDataAddDTO
     * @param beforeSaveVO   保存之前的方法返回的数据
     * @param saveVO         保存方法返回的数据
     * @return com.xbongbong.pro.formdata.pojo.vo.SaveVO
     * @throws XbbException
     */
    @Override
    public FormDataAddVO afterSaveForWorkflow(FormDataAddDTO formDataAddDTO, BeforeSaveVO beforeSaveVO, SaveVO saveVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity) throws XbbException {
        FormDataAddVO formDataAddVO = new FormDataAddVO();
        Long dataId = saveVO.getDataId();
        String corpid = formDataAddDTO.getCorpid();
        Integer saasMark = formDataAddDTO.getSaasMark();
        Integer businessType = formDataAddDTO.getBusinessType();
        try {
            SaasFormSaveDTO saasFormSaveDTO = new SaasFormSaveDTO();
            BeanUtil.copyProperties(formDataAddDTO, saasFormSaveDTO);
            packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
            saasFormSaveDTO.setSaasNeedRedundantAttrPoJo(beforeSaveVO.getSaasNeedRedundantAttrPojo());
            costAdjustService.afterSaveForWorkflow(saasFormSaveDTO);

            formDataAddVO.setDataId(saveVO.getDataId());
            formDataAddVO.setFormDataId(saveVO.getDataId());
            formDataAddVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_RETURN_MSG));
            formDataAddVO.setCode(PaasConstant.FORM_ADD_RETURN_CODE);
            return formDataAddVO;
        } catch (XbbException e) {
            LOG.warn(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(), e);
            saveRollBack(dataId, corpid, saasMark, businessType);
            throw e;
        } catch (Exception e) {
            LOG.error(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(), e);
            saveRollBack(dataId, corpid, saasMark, businessType);
            throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200018);
        }
    }
}
